package com.htfyun.roobofactory.factorytest;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.htfyun.roobofactory.BaseActivity;
import com.htfyun.roobofactory.R;
import com.htfyun.roobofactory.config.AppConfig;
import com.htfyun.roobofactory.config.RooboBuildConfig;
import com.htfyun.roobofactory.utils.PermissionManager;
import com.htfyun.roobofactory.wifilibrary.WiFiManager;
import com.htfyun.roobofactory.wifilibrary.listener.OnWifiConnectListener;
import com.htfyun.roobofactory.wifilibrary.listener.OnWifiEnabledListener;
import com.htfyun.roobofactory.wifilibrary.listener.OnWifiScanResultsListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * Created by sst on 2018/7/9.
 */

public class WifiTestActivity extends BaseActivity  implements SwipeRefreshLayout.OnRefreshListener,
        AdapterView.OnItemClickListener,
        AdapterView.OnItemLongClickListener{

    private TextView txtStatus;
    private TextView txtConnectedSSID;
    private TextView txtAutoTestSSID;

    private Button btnPass;
    private Button btnFail;

    private ListView mWifiListView;
    private WifiListAdapter mWifiListAdapter;

    private SwipeRefreshLayout swipeRefreshLayout;

    private WiFiManager mWiFiManager;

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_factorytest_wifi);

        btnPass = (Button) findViewById(R.id.btnPass);
        btnFail = (Button) findViewById(R.id.btnFail);
        btnPass.setOnClickListener(onPassOrFailClickListener);
        btnFail.setOnClickListener(onPassOrFailClickListener);

        btnPass.setVisibility(RooboBuildConfig.FT_ADD_PASS_BTN ? View.VISIBLE : View.GONE);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(this);

        txtStatus = (TextView) findViewById(R.id.txtStatus);
        txtConnectedSSID = (TextView) findViewById(R.id.txtConnectedSSID);
        txtAutoTestSSID = (TextView) findViewById(R.id.txtAutoTestSSID);
        txtAutoTestSSID.setText(getString(R.string.test_scan_wifi_ssid, AppConfig.WIFI_SSID_PASSED));

        mWifiListView = (ListView) findViewById(R.id.wifiListView);
        mWifiListView.setEmptyView(findViewById(R.id.empty_view));
        mWifiListAdapter = new WifiListAdapter(getApplicationContext());
        mWifiListView.setAdapter(mWifiListAdapter);
        mWifiListView.setOnItemClickListener(this);
        mWifiListView.setOnItemLongClickListener(this);

        mContext = this;
        mWiFiManager = WiFiManager.getInstance(mContext);

        mWiFiManager.setOnWifiEnabledListener(new OnWifiEnabledListener() {
            @Override
            public void onWifiEnabled(boolean enabled) {
                int statusResId = R.string.wifi_status_off;
                if (enabled) {
                    statusResId = R.string.wifi_status_on;
                    mWiFiManager.startScan();
                }

                txtStatus.setText(getString(R.string.test_wifi_status, getString(statusResId)));

            }
        });

        mWiFiManager.setOnWifiConnectListener(new OnWifiConnectListener() {
            @Override
            public void onWiFiConnectLog(String log) {
                Log.e(TAG, "onWiFiConnectLog = " + log);
            }

            @Override
            public void onWiFiConnectSuccess(String SSID) {

                String str = mContext.getString(R.string.wifi_success_to_connect_ssid, SSID);
                Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();

                txtConnectedSSID.setText(mContext.getString(R.string.test_wifi_connected_ssid, SSID));

                mWifiListAdapter.setConnectedSSID(SSID);
            }

            @Override
            public void onWiFiConnectFailure(String SSID) {

                if (!(TextUtils.isEmpty(SSID) || SSID.contains("unknown"))) {

                    String str = mContext.getString(R.string.wifi_fail_to_connect_ssid, SSID);
                    Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
                }

                txtConnectedSSID.setText(mContext.getString(R.string.test_wifi_connected_ssid, ""));

                mWifiListAdapter.setConnectedSSID("");

            }
        });

        mWiFiManager.setOnWifiScanResultsListener(new OnWifiScanResultsListener() {
            @Override
            public void onScanResults(List<ScanResult> scanResults) {
                refreshData(scanResults);

                for (ScanResult scanResult : scanResults) {
                    String ssid = scanResult.SSID.replaceAll("\"", "");
                    if (scanResult.level > (AppConfig.WIFI_RSSI_MIN)
                            && (ssid.equals(AppConfig.WIFI_SSID_PASSED) || ssid.equals(AppConfig.WIFI_SSID_PASSED_HTFYUN))) {

                        startAutoPass(R.string.test_wifi_pass);
                        break;
                    }
                }

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        mWiFiManager.registerWifiReceiver(mContext);

        initPermission();

    }

    @Override
    protected void onPause() {
        super.onPause();

        mWiFiManager.unregisterWifiReceiver(mContext);

    }

    private View.OnClickListener onPassOrFailClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btnPass) {

                setResult(RESULT_OK);
                ActivityCompat.finishAfterTransition(getActivity());

            } else if (v == btnFail) {

                setResult(RESULT_CANCELED);
                ActivityCompat.finishAfterTransition(getActivity());

            }
        }
    };



    private void initPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            //同时申请多个权限
            PermissionManager.getInstance(getApplicationContext()).execute(this,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION);

        } else {

            wifiStartScanAfterPermission();

        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance(getApplicationContext()).
                onRequestPermissionsResult(requestCode, permissions, grantResults);

        Log.e(TAG, "bluetooth ~~~~~~~~~~~~~~onRequestPermissionsResult");

        wifiStartScanAfterPermission();


    }

    private void wifiStartScanAfterPermission() {

        int statusResId = R.string.wifi_status_on;

        if (!mWiFiManager.isWifiEnabled()) {
            statusResId = R.string.wifi_status_off;
            mWiFiManager.openWiFi();
        } else {

            mWiFiManager.startScan();
        }

        txtStatus.setText(getString(R.string.test_wifi_status, getString(statusResId)));
    }

    @Override
    public void onRefresh() {
        // 下拉刷新
        mWiFiManager.startScan();

        mWifiListAdapter.clearData();

    }

    /**
     * WIFI列表单击
     *
     * @param parent   parent
     * @param view     view
     * @param position position
     * @param id       id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        final ScanResult scanResult = (ScanResult) mWifiListAdapter.getItem(position);
//        switch (mWiFiManager.getSecurityMode(scanResult)) {
//            case WPA:
//            case WPA2:
//                new ConnectWifiDialog(this) {
//
//                    @Override
//                    public void connect(String password) {
//                        boolean ret = mWiFiManager.connectWPA2Network(scanResult.SSID, password);
//                        Log.e(TAG, "WPA2 ret = " + ret);
//                    }
//                }.setSsid(scanResult.SSID).show();
//                break;
//            case WEP:
//                new ConnectWifiDialog(this) {
//
//                    @Override
//                    public void connect(String password) {
//                        boolean ret = mWiFiManager.connectWEPNetwork(scanResult.SSID, password);
//                        Log.e(TAG, "WEP ret = " + ret);
//
//                    }
//                }.setSsid(scanResult.SSID).show();
//                break;
//            case OPEN: // 开放网络
//                mWiFiManager.connectOpenNetwork(scanResult.SSID);
//                break;
//        }
    }

    /**
     * WIFI列表长按
     * @param parent
     * @param view
     * @param position
     * @param id
     * @return
     */
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//        ScanResult scanResult = (ScanResult) mWifiListAdapter.getItem(position);
//        final String ssid = scanResult.SSID;
//
//        new AlertDialog.Builder(this)
//                .setTitle(ssid)
//                .setItems(R.array.wifi_items_long_click, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        switch (which) {
//                            case 0: // 断开连接
//                                WifiInfo connectionInfo = mWiFiManager.getConnectionInfo();
//                                Log.i(TAG, "onClick: connectionInfo :" + connectionInfo.getSSID());
//                                if (mWiFiManager.addDoubleQuotation(ssid).equals(connectionInfo.getSSID())) {
//                                    mWiFiManager.disconnectWifi(connectionInfo.getNetworkId());
//                                } else {
//                                    String toast = mContext.getString(R.string.wifi_does_not_connect_ssid, ssid);
//                                    Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
//                                }
//                                break;
//                            case 1: // 删除网络配置
//                                WifiConfiguration wifiConfiguration = mWiFiManager.getConfigFromConfiguredNetworksBySsid(ssid);
//                                if (null != wifiConfiguration) {
//                                    boolean isDelete = mWiFiManager.deleteConfig(wifiConfiguration.networkId);
//
//                                    Toast.makeText(getApplicationContext(), isDelete ? R.string.wifi_delete_ok : R.string.wifi_delete_need_root, Toast.LENGTH_SHORT).show();
//                                } else {
//                                    Toast.makeText(getApplicationContext(), R.string.wifi_not_saved, Toast.LENGTH_SHORT).show();
//                                }
//                                break;
//                            default:
//                                break;
//                        }
//                    }
//                }).show();
        return true;
    }


    private void refreshData(List<ScanResult> scanResults) {
        swipeRefreshLayout.setRefreshing(false);
        // 刷新界面
        mWifiListAdapter.refreshData(scanResults);
    }


    private final class WifiListAdapter extends BaseAdapter {

        private static final String TAG = "WifiListAdapter";
        private List<ScanResult> scanResults;
        private Context mContext;
        private String connectedSSID;

        public WifiListAdapter(Context context) {
            mContext = context.getApplicationContext();
            this.scanResults = new ArrayList<>();
        }

        public String getConnectedSSID() {
            return connectedSSID;
        }

        public void setConnectedSSID(String connectedSSID) {
            this.connectedSSID = connectedSSID;

            refreshData(getScanResults());

        }


        public List<ScanResult> getScanResults() {
            return scanResults;
        }

        private List<ScanResult> getNewScanResultBySetConnectedSSIDFist(List<ScanResult> scanResults) {

            Collections.sort(scanResults, new Comparator<ScanResult>() {
                @Override
                public int compare(ScanResult o1, ScanResult o2) {
                    return o2.level- o1.level;
                }
            });

            if (TextUtils.isEmpty(connectedSSID)) {

                return scanResults;
            }

            Iterator<ScanResult> it = scanResults.iterator();

            ScanResult first = null;
            while(it.hasNext()){
                ScanResult x = it.next();

                if(x.SSID.replaceAll("\"", "").equals(connectedSSID.replaceAll("\"", ""))){
                    it.remove();
                    first = x;
                    break;
                }
            }

            if (first != null) {
                scanResults.add(0, first);

            }

            return scanResults;

        }

        public void clearData() {
            scanResults.clear();
            notifyDataSetChanged();
        }

        public void refreshData(List<ScanResult> scanResults) {
            if (null != scanResults) {
                // 去重
                List<ScanResult> newScanResults = WiFiManager.excludeRepetition(scanResults);

                // 清空数据
                this.scanResults.clear();
                // 更新数据
                this.scanResults.addAll(getNewScanResultBySetConnectedSSIDFist(newScanResults));
            }
            // 更新显示
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return scanResults.size();
        }

        @Override
        public Object getItem(int position) {
            return scanResults.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView != null) {
                holder = (ViewHolder)convertView.getTag();
            }

            if (holder == null) {
                holder = new ViewHolder();
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_wifi_devices, null);
                holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
                holder.txtRSSI = (TextView) convertView.findViewById(R.id.txtRSSI);
                holder.txtCapabilities = (TextView) convertView.findViewById(R.id.txtCapabilities);

                convertView.setTag(holder);
            }

            ScanResult scanResult = scanResults.get(position);

            holder.txtName.setText(getString(R.string.wifi_rssi_name, scanResult.SSID));
            Log.e(TAG, "level = " + scanResult.level);

            holder.txtRSSI.setText(getString(R.string.wifi_signal_strength, scanResult.level));//(WifiManager.calculateSignalLevel(scanResult.level, 5) + "/5")));
            holder.txtCapabilities.setText(getString(R.string.wifi_capabilities, scanResult.capabilities));

            return convertView;
        }
    }

    private class ViewHolder {
        private TextView txtName;
        private TextView txtRSSI;
        private TextView txtCapabilities;
    }

}
